package com.example.java_controller;

import com.example.java_pojo.User;
import com.example.java_service.UserService;
import com.example.java_util.utils.CaptchaUtil;
import com.example.java_util.utils.Code;
import com.example.java_util.utils.CookieUtil;
import com.example.java_util.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
@ComponentScan({"com.example.java_service"})
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result save(@RequestBody User user) {
        boolean flag = userService.save(user);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        boolean flag = userService.update(user);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = userService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user != null ? "" : "数据查询失败，请重试";
        return new Result(code, user, msg);
    }

    @GetMapping
    public Result findAll() {
        List<User> userList = userService.findAll();
        Integer code = userList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = userList != null ? "" : "数据查询失败，请重试";
        return new Result(code, userList, msg);
    }

    @PostMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String value = request.getParameter("value");
        System.out.println(username + password + (value.equals("1")));
        if (value.equals("1")) {
            Cookie c_username = new Cookie("username", username);
            Cookie c_password = new Cookie("password", password);
            c_username.setMaxAge(60 * 60);
            c_password.setMaxAge(60 * 60);
            c_username.setPath("/");
            c_password.setPath("/");
            response.addCookie(c_username);
            response.addCookie(c_password);
        }
        User user = userService.login(username, password);
        Integer code = user != null ? Code.LOGIN_OK : Code.LOGIN_ERR;
        String msg = code != 20050 ? "登录成功" : "登录失败";
        return new Result(code, user, msg);
    }

    @GetMapping("/get")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String securityCode = CaptchaUtil.getSecurityCode();
        //将验证码放入session
        String id = session.getId();
//        log.info("session id:{}",id);
        session.setAttribute("checkCode", securityCode);
        //生成图片
        BufferedImage image = CaptchaUtil.createImage(securityCode);
        //输出图片
        ServletOutputStream outputStream = response.getOutputStream();
        //调用工具类
        ImageIO.write(image, "png", outputStream);
//        log.info("获取验证码成功!!!");
    }

    @PostMapping("/register")
    public Result register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("inputcode" + code);
        HttpSession session = request.getSession();
        String checkCode = (String) session.getAttribute("checkCode");
        System.out.println(checkCode);
        session.removeAttribute("checkCode");
        if (checkCode.equals(code)) {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            boolean flag = userService.save(user);
            String msg = "注册成功";
            return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, msg);
        } else {
            String msg = "验证码错误";
            return new Result(Code.CHECK_ERR, msg);
        }
    }

}
